// pages/card-create-modify/cropper/cropper.js

const util = require("../../../utils/util");
const api = require("../../../config/api");
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: 0,
    width: 250,
    height: 300,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.cropper = this.selectComponent("#image-cropper");
    this.setData({
      CustomBar: app.globalData.CustomBar,
    });
    this.cropper.upload(); //上传图片
  },

  /**
   * 裁剪图片组件初始化完成
   */
  cropperload: function () {
    console.log('cropper加载完成');
  },

  /**
   * 图片加载完成
   */
  loadimage: function (e) {
    wx.hideLoading();
    console.log('图片', e);
    this.cropper.imgReset();
  },

  /**
   * 点击中间裁剪框
   */
  clickcut: function (e) {
    console.log(e.detail);
    //图片预览
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url] // 需要预览的图片http链接列表
    })
  },

  /**
   * 图片放大
   */
  enlarge() {
    this.data.enlarge = setInterval(() => {
      this.cropper.setTransform({
        scale: 0.02
      });
    }, 1000 / 60)
  },

  /**
   * 图片缩小
   */
  narrow() {
    this.data.narrow = setInterval(() => {
      this.cropper.setTransform({
        scale: -0.02
      });
    }, 1000 / 60)
  },

  /**
   * 结束图片放大缩小
   */
  end(e) {
    clearInterval(this.data[e.currentTarget.dataset.type]);
  },

  /**
   * 点击取消
   */
  cancel: function () {
    console.log('取消裁剪')
    wx.navigateBack({
      delta: -1,
    })
  },

  /**
   * 点击提交图片并返回上一页
   */
  submit: function () {
    this.cropper.getImg((obj) => {
      app.globalData.result = obj.url;
      this.uploadAvatar(obj.url);
    });
  },

  /**
   * 上传头像
   */
  uploadAvatar: function (filePath) {
    let employeeInfo = app.globalData.employeeInfo;
    wx.uploadFile({
      filePath: filePath,
      name: 'file',
      url: api.urls.addAttch,
      header: {
        'content-type': 'multipart/form-data'
      },
      formData: {
        'attachType': 'image',
        'operatorId': employeeInfo ? employeeInfo.id : '',
        'relationType': 'userHeadImg'
      },
      success: res => {
        let data = JSON.parse(res.data)
        if (data.code != 0) {
          util.showToast(data.msg, 'none');
          return;
        }
        util.showToast("上传成功", 'success');
        app.globalData.headImg = data.data.attachUrl;
        if(null != app.globalData.employeeInfo) {
            app.globalData.employeeInfo.headImgUrl = api.picUrl + data.data.attachUrl;
        }
        setTimeout(() => {
          wx.navigateBack({
            delta: -1
          })
        }, 1500)
      }
    })
  }
})